﻿using System;
using System.IO;
using System.Text;
using System.Web.Mvc;
using Kevin.Shop.Business.Service.Entity.SalesManagement.Order;
using WeixinPay.Business;
using WeixinPay.Models;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.TenPayLibV3;
using System.Xml.Linq;
using Kevin.Shop.Business.Service.Entity.Helper;
using Senparc.Weixin.MP;
using System.Configuration;
using WeixinPay.Business.wxPay;

namespace WeixinPay.Controllers
{
    public class wxpayController : Controller
    {
        //
        // GET: /Default1/

        public ActionResult Index()
        {
            return Content("ok");
        }

        //
        // POST: /Default1/Create

        [HttpPost]
        public ActionResult notify(FormCollection collection)
        {
            return Content("success");
        }

        [HttpPost]
        public ActionResult warning(FormCollection collection)
        {
            return Content("success");
        }

        public ActionResult test()
        {
            return Content("test");
        }

        private static TenPayV3Info _tenPayV3Info;

        public static TenPayV3Info TenPayV3Info
        {
            get
            {
                if (_tenPayV3Info == null)
                {
                    _tenPayV3Info = new TenPayV3Info(ConfigurationManager.AppSettings["TenPayV3_AppId"],
                                                    ConfigurationManager.AppSettings["TenPayV3_AppId"],
                                                    ConfigurationManager.AppSettings["TenPayV3_MchId"],
                                                    ConfigurationManager.AppSettings["TenPayV3_Key"], string.Empty);//TenPayV3InfoCollection.Data[System.Configuration.ConfigurationManager.AppSettings["TenPayV3_MchId"]];
                }
                return _tenPayV3Info;
            }
        }

        public ActionResult tgpayjsapi(string orderNumber = "0")
        {
            //string appId;
            //string timeStamp;
            //string nonceStr;
            //string packageStr;
            //string signType;
            //string sign;
            //string string1;

            //appId = Config.AppId;
            //timeStamp = Utils.GetTimestamp();
            //nonceStr = Utils.GetNonceStr();
            //signType = "SHA1";


            //var order = ServiceHelper.GetOrderDetailInfo(orderNumber);
            //var package = new Package(order);
            //packageStr = package.GetPackageString();

            //string1 = string.Format(
            //    "appid={0}&appkey={1}&noncestr={2}&package={3}&timestamp={4}",
            //    appId, Config.AppKey, nonceStr, packageStr, timeStamp);

            //sign = Kevin.Comm.Strings.StringFunction.NoneEncrypt(string1, 0).ToLower();

            //ViewBag.AppId = TenPayV3Info.AppId; ;
            //ViewBag.timeStamp = timeStamp;
            //ViewBag.NonceStr = nonceStr;
            //ViewBag.Package = string.Format("prepay_id={0}", prepayId); ;
            //ViewBag.SignType = "MD5";
            //ViewBag.Sign = paySignReqHandler.CreateMd5Sign("key", TenPayV3Info.Key); ;

            return View();
        }
        
        [HttpPost]
        public ActionResult notifyurl()
        {
            try
            {
                //Url信息
                var sign = Request.Form["sign"];
                var trade_mode = Request.Form["trade_mode"];
                var trade_state = Request.Form["trade_state"];
                var partner = Request.Form["partner"];
                var bank_type = Request.Form["bank_type"];
                var total_fee = Request.Form["total_fee"];
                var fee_type = Request.Form["fee_type"];
                var notify_id = Request.Form["notify_id"];
                var transaction_id = Request.Form["transaction_id"];
                var out_trade_no = Request.Form["out_trade_no"];
                var time_end = Request.Form["time_end"];

                //PostData信息
                var receivedData = new ReceivedData(Request, 1);
                Kevin.Comm.Logger.Tracer.TraceLog(receivedData.RawXml, "weixinPayNotify", "weixinPayNotify", false);

                if (receivedData.Result_code.ToUpper() == "SUCCESS")  //支付成功
                {
                    OrderPaymentInfo info = null;
                    if (!string.IsNullOrEmpty(out_trade_no))
                    {
                        info = new OrderPaymentInfo
                        {
                            OrderNumber = out_trade_no,
                            TradeNumber = transaction_id,
                            TransferAmount = Convert.ToDecimal(total_fee) / 100,
                            InDate = DateTime.Now,
                            BuyerPaymentID = receivedData.OpenId,
                            InUser = 100
                        };
                    }
                    else
                    {
                        info = new OrderPaymentInfo
                        {
                            OrderNumber = receivedData.OrderNumber,
                            TradeNumber = receivedData.Transaction_id,
                            TransferAmount = Convert.ToDecimal(receivedData.Total_fee) / 100,
                            InDate = DateTime.Now,
                            BuyerPaymentID = receivedData.OpenId,
                            InUser = 100
                        };
                    } 
                    var response = ServiceHelper.CreateOrderPaymentInfo(info);
                    //2.发货通知，O2O支付成功就立即调用发货接口
                    //2.1.获取AccessToken
                    var utils = new Utils();
                    var access_token = utils.GetAccessToken();

                    //2.2.向微信发送发货通知
                    var strMsg = utils.SendDeliverNotify(access_token, receivedData.OpenId, receivedData.Transaction_id, receivedData.OrderNumber);
                    Response.Write("success 后台通知成功");
                    //return Redirect(ConfigurationManager.AppSettings["TenPayV3_PaymentCompleted"]);
                }
                else
                {
                    Response.Write("支付失败");
                }
            }
            catch (Exception ex)
            {
                Kevin.Comm.Logger.Tracer.Error(ex);
                return Content("fail:" + ex.ToString());
            }
            return View();
        }

        private bool Notify()
        {
            WxPayResponseHandler resHandler = new WxPayResponseHandler(this.Request);
                resHandler.init();
                resHandler.setKey(WxPayUtil.key, WxPayUtil.appkey);

                //判断签名
                if (resHandler.isTenpaySign())
                {

                    if (resHandler.isWXsign())
                    {
                        //商户在收到后台通知后根据通知ID向财付通发起验证确认，采用后台系统调用交互模式
                        string notify_id = resHandler.getParameter("notify_id");
                        //取结果参数做业务处理
                        string out_trade_no = resHandler.getParameter("out_trade_no");
                        //财付通订单号
                        string transaction_id = resHandler.getParameter("transaction_id");
                        //金额,以分为单位
                        string total_fee = resHandler.getParameter("total_fee");
                        //如果有使用折扣券，discount有值，total_fee+discount=原请求的total_fee
                        string discount = resHandler.getParameter("discount");
                        //支付结果
                        string trade_state = resHandler.getParameter("trade_state");
                        string openid = resHandler.getParameter("openid");
                        //即时到账
                        if ("0".Equals(trade_state))
                        {
                            //------------------------------
                            //处理业务开始
                            //------------------------------

                            //处理数据库逻辑
                            //注意交易单不要重复处理
                            //注意判断返回金额


                            //Kevin.Comm.Logger.Tracer.TraceLog(receivedData.RawXml, "weixinPayNotify", "weixinPayNotify", false);

                            if (trade_state == "0")  //支付成功
                            {
                                OrderPaymentInfo info = null;
                                if (!string.IsNullOrEmpty(out_trade_no))
                                {
                                    info = new OrderPaymentInfo
                                    {
                                        OrderNumber = out_trade_no,
                                        TradeNumber = transaction_id,
                                        TransferAmount = Convert.ToDecimal(total_fee) / 100,
                                        InDate = DateTime.Now,
                                        BuyerPaymentID = openid,
                                        InUser = 100
                                    };
                                }

                                var response = ServiceHelper.CreateOrderPaymentInfo(info);
                                //2.发货通知，O2O支付成功就立即调用发货接口
                                //2.1.获取AccessToken
                                var utils = new Utils();
                                var access_token = utils.GetAccessToken();

                                //2.2.向微信发送发货通知
                                var strMsg = utils.SendDeliverNotify(access_token, openid, transaction_id, out_trade_no);

                                //------------------------------
                                //处理业务完毕
                                //------------------------------
                                //给财付通系统发送成功信息，财付通系统收到此结果后不再进行后续通知
                                Response.Write("success 后台通知成功");

                                return true;
                            }
                            else
                            {
                                Response.Write("支付失败");
                            }
                            //回复服务器处理成功
                            Response.Write("success");
                        }
                        else
                        {//SHA1签名失败
                            Response.Write("fail -SHA1 failed");
                            Response.Write(resHandler.getDebugInfo());
                        }

                    }

                    else
                    {//md5签名失败
                        Response.Write("fail -md5 failed");
                        Response.Write(resHandler.getDebugInfo());
                    }
                }
                return false;
        }

        private void Log(string rawXml, string strMsg)
        {
            string temp = string.Empty;
            temp += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            temp += "\n" + rawXml + "\n";
            temp += strMsg + "\n";
            temp += Request.Url + "\n\n";
            var filepath = Server.MapPath("/") + "log\\" + DateTime.Now.ToLongDateString() + "log.txt";
            FileStream fs = new FileStream(filepath, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            sw.Write(temp);
            sw.Close();
            fs.Close();
        }
    }                        
}                            